package com.zb.service.imp.base;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zb.dao.base.OmsCommonDao;
import com.zb.dao.ext.system.OmsNormalSpListRepo;
import com.zb.dao.ext.system.OmsOperListDao;
import com.zb.entity.base.JsonCommon;
import com.zb.entity.base.JsonForList;
import com.zb.entity.base.OmsCommonParam;
import com.zb.entity.base.OmsEntityEnum;
import com.zb.entity.base.OmsMerchantList;
import com.zb.entity.exception.BizException;
import com.zb.entity.exception.OmsDaoException;
import com.zb.entity.system.OmsNormalSpListEntity;
import com.zb.entity.system.OmsOperMerchant;
import com.zb.entity.system.OmsOperationSpListEntity;
import com.zb.service.base.MerchantListService;
import com.zb.tcp.rpc.ms.SystemMasterServerRpcClient;
import com.zb.tcp.rpc.ms.client.entity.MasterMerchant;
import com.zb.tcp.rpc.ms.client.entity.MasterMerchantParam;
import com.zb.tcp.rpc.ms.client.entity.MasterMerchantResult;
import com.zb.util.OmsConstant.MsgCodeEnum;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class MerchantListServiceImpl extends BaseService implements MerchantListService
{
	private static final int MERCHANT_ID_SUB_LENGTH = 13;
	@Autowired
	@Qualifier("base")
	private OmsCommonDao<OmsMerchantList> commonDaoImpl;
	@Autowired
	private OmsOperListDao operListDao;
//	@Autowired
//	private SystemMasterServerRpcClient systemMasterServerRpcClient;

	@Autowired
	private OmsNormalSpListRepo omsNormalSpListRepo;

	@Override
	public synchronized JsonCommon<?> add(OmsMerchantList merchant)
	{
		String lastId = null;
		try
		{
			lastId = commonDaoImpl.findMaxPkIdBySingle(MERCHANT_ID_SUB_LENGTH, OmsMerchantList.class);
			lastId = this.genarateCurrentId(lastId, merchant);
			if (StringUtils.isNotEmpty(lastId))
			{
				merchant.setMerchant_id(lastId);
				commonDaoImpl.add(merchant);
			}
			else
			{
				return this.buildOtherJsonCommon(MsgCodeEnum.ERROR400.getMsgCode(), "genarate id error!!!");
			}

		}
		catch (OmsDaoException e)
		{
			logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
		return this.buildSuccessJsonCommon(merchant);
	}

	@Override
	public JsonCommon<?> update(OmsMerchantList merchant)
	{
		try
		{
			commonDaoImpl.update(merchant);
		}
		catch (OmsDaoException e)
		{
			logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
		return this.buildSuccessJsonCommon(merchant);
	}

	@Override
	public JsonCommon<?> delete(String id)
	{
		try
		{
			commonDaoImpl.deleteById(id, OmsMerchantList.class);
			//商户被删除，相关用户被删除。
			operListDao.logicDelOperByEntity(OmsEntityEnum.MERCHANT.getValue(), id);
		}
		catch (OmsDaoException e)
		{
			logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
		return this.buildSuccessJsonCommon("success");
	}

	@Override
	public JsonForList<?> findMerchantLstPage(OmsCommonParam param, OmsMerchantList merchant)
	{
		try
		{
			List<OmsMerchantList> lst = commonDaoImpl.pagingFind(param, merchant);
			int total = 0;
			if (param.isQueryTotal())
			{
				total = commonDaoImpl.queryTotalByObject(merchant);
			}
			return this.buildSuccessJsonForList(param, lst, total);
		}
		catch (Exception e)
		{
			logError(e.getMessage(), e);
			return this.buildError400JsonForList();
		}
	}

	@Override
	public JsonCommon<?> findMerchantById(String id)
	{
		if (StringUtils.isEmpty(id))
		{
			return this.buildOtherJsonCommon(MsgCodeEnum.ERROR400.getMsgCode(), "Error:the request id is empty");
		}
		try
		{
			OmsMerchantList m = new OmsMerchantList();
			m.setMerchant_id(id);
			OmsMerchantList op = commonDaoImpl.findRecordByPK(m);
			return this.buildSuccessJsonCommon(op);
		}
		catch (Exception e)
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
	}

	@Override
	public void syncPartnerFromMasterServer() throws BizException
	{
		MasterMerchantParam paramVO = new MasterMerchantParam();
		paramVO.setStartTime("1900-01-01");
		paramVO.setProviderType(2);
		/*
		MasterMerchantResult retVO = systemMasterServerRpcClient.systemQueryMerchantInteface(paramVO);
		if (retVO.getIsSuccess() == 1)
		{

			List<MasterMerchant> list_ms = retVO.getResult();

			List<String> valid_ms_list = new ArrayList<>();
			for (MasterMerchant ms : list_ms)
			{
				if (ms.getIsValid() == 1)
					valid_ms_list.add(ms.getMerchantCode());
			}

			List<OmsNormalSpListEntity> all_merchant_list = omsNormalSpListRepo.findAll();

			List<String> valid_merchant_list = new ArrayList<>();
			for (OmsNormalSpListEntity e : all_merchant_list)
			{
				if (e.getValidFlag() != null && e.getValidFlag() == 1)
					valid_merchant_list.add(e.getMerchantId());
			}

			List<String> delete_list = new ArrayList<>(valid_merchant_list);
			delete_list.removeAll(valid_ms_list);

			List<String> update_list = new ArrayList<>(valid_merchant_list);
			update_list.retainAll(valid_ms_list);

			List<String> add_list = new ArrayList<>(valid_ms_list);
			add_list.removeAll(valid_merchant_list);

			Date now = new Date();
			Random r = new Random();

			for (OmsNormalSpListEntity e : all_merchant_list)
			{
				if (delete_list.contains(e.getMerchantId()))
				{
					e.setValidFlag(0);
					e.setUpdateTime(now);
					e.setUpdateOperId("SyncWithMS");
				}
				else if (update_list.contains(e.getMerchantId()))
				{
					MasterMerchant ms = findMasterMerchant(list_ms, e.getMerchantId());
					e.setAddress(ms.getAddress());
					e.setName(ms.getName());
					e.setDistrictCode(ms.getDistrictCode());
					e.setEntityType(ms.getIsSelf());
					e.setUpdateTime(now);
					e.setUpdateOperId("SyncWithMS");
					if (ms.getIsSelf() == 1)
						e.setEntityType(0);
					else if (ms.getIsSelf() == 0)
						e.setEntityType(1);
				}
				else if (add_list.contains(e.getMerchantId()))
				{
					MasterMerchant ms = findMasterMerchant(list_ms, e.getMerchantId());

					e.setValidFlag(1);
					e.setAddress(ms.getAddress());
					e.setName(ms.getName());
					e.setDistrictCode(ms.getDistrictCode());
					e.setUpdateTime(now);
					e.setUpdateOperId("SyncWithMS");
					if (ms.getIsSelf() == 1)
						e.setEntityType(0);
					else if (ms.getIsSelf() == 0)
						e.setEntityType(1);

					add_list.remove(e.getMerchantId());
				}
			}

			if (!add_list.isEmpty())
			{
				List<OmsNormalSpListEntity> add_entity_list = new ArrayList<>();
				for (String merchantCode : add_list)
				{
					MasterMerchant ms = findMasterMerchant(list_ms, merchantCode);

					OmsNormalSpListEntity entity = new OmsNormalSpListEntity();

					entity.setCreateTime(now);
					entity.setCreateOperId("SyncWithMS");

					entity.setMerchantId(ms.getMerchantCode());
					entity.setAddress(ms.getAddress());
					entity.setName(ms.getName());
					entity.setDistrictCode(ms.getDistrictCode());
					entity.setValidFlag(1);
					entity.setUpdateTime(now);
					entity.setUpdateOperId("SyncWithMS");
					if (ms.getIsSelf() == 1)
						entity.setEntityType(0);
					else if (ms.getIsSelf() == 0)
						entity.setEntityType(1);
					add_entity_list.add(entity);
				}
				if (!add_entity_list.isEmpty())
					omsNormalSpListRepo.save(add_entity_list);
			}
			omsNormalSpListRepo.save(all_merchant_list);
		}
		*/
	}

	private MasterMerchant findMasterMerchant(List<MasterMerchant> list_ms, String merchantCode)
	{
		MasterMerchant m = null;
		for (MasterMerchant ms : list_ms)
		{
			if (ms.getMerchantCode().equals(merchantCode))
			{
				m = ms;
				break;
			}
		}
		return m;
	}

	/**
	 * 生成商户的业务规则Id
	 * 业务id生成规则：
	 * 商户id规则：6位区县代码+1位实体类型+13位自增(自增长)
	 *
	 * @param id
	 * @param merchant
	 * @return
	 */
	private String genarateCurrentId(String id, OmsMerchantList merchant)
	{
		try
		{
			if (merchant != null)
			{
				String gid = genarateId(id, MerchantListServiceImpl.MERCHANT_ID_SUB_LENGTH);
				if (StringUtils.isNotEmpty(gid))
				{
					StringBuilder idSb = new StringBuilder();
					idSb.append(merchant.getDistrict_code()).
							append(merchant.getEntity_type()).append(gid);
					return idSb.toString();
				}
			}
		}
		catch (OmsDaoException e)
		{
			this.logError(e.getMessage(), e);
		}
		return null;
	}

}
